﻿/**********************************************
 * 功能名称：原材料的领用及盘存的变动调整
编写人：  杨莹
建立时间： 杨 2009年2月18日
说明：
加载页面时，根据当前用户ID查询出责任部门，列表显示其作业中心列表。
作业中心列表中选择后，列表出作业中心中间体；
选择作业中心中间体，列表当前中间体的材料列表。
用户可手工调整当前材料的所有信息并可以删除。
 **************************************************************/

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Hisun.Models;
using Hisun.Controllers;
using System.Collections.Generic;

namespace Hisun.View.Meterial
{
    public partial class DirectMeterialModify : AbcPageBase
    {
        HisunDBDataContext db = new HisunDBDataContext();

        public string alert;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                var CurrentUserCenterId = (from a in db.TAbc_JS_Users where a.操作员ID == Session[ServerVars.sysSessionUserName].ToString() select new { a.责任部门ID }).Single();
                dropCostCenterSelect.Items.Clear();
                var myquery = from a in db.TABC_JS_CostCenter select a;
                FillData2DropDownList(Convert.ToInt32(CurrentUserCenterId.责任部门ID), myquery);
             //   BindData();
                TextBox_AccountPeriod.Text = Application["accountPeriod"].ToString();


            }
        }

        //查询当前操作员对应的作业中心列表
        private void FillData2DropDownList(int CenterID, IEnumerable<TABC_JS_CostCenter> TotalTrees)
        {
            var Mylist = (from m in TotalTrees where m.上级作业中心ID == CenterID select m).ToList();

            if (Mylist.Count() == 0)
                return;
            foreach (var MylistItem in Mylist)
            {
                ListItem InsertItem = new ListItem(MylistItem.作业中心名称, MylistItem.作业中心ID.ToString());
                FillData2DropDownList(MylistItem.作业中心ID, TotalTrees);


                if (new string[] { "A", "BF", "BG", "BH", "BZ" }.Contains(MylistItem.类型) && MylistItem.停用 == false)
                {
                    dropCostCenterSelect.Items.Add(InsertItem);
                }

            }
        }

        //绑定数据来源
        protected void Button_Query_Click(object sender, EventArgs e)
        {
            BindData();
        }



        private void BindData()
        {
            HiddenField_CenterId.Value = dropCostCenterSelect.SelectedValue;
            HiddenField_PIPId.Value = DropDownListSelectProductInProccess.SelectedValue;
            HiddenField_Ap.Value = TextBox_AccountPeriod.Text;

            string CenterId = HiddenField_CenterId.Value.ToString();
            string PIPId = HiddenField_PIPId.Value.ToString();
            string MyAp = HiddenField_Ap.Value;



            //建立视图，查询出前作业中心的，中间产品材料的期初、领用、消耗、盘存信息。
        
            if (CheckBox_Shift.Checked == true)
            {
               var  MyMeterialQuery1 = from a in db.TABC_JC_MeterialResumption
                                   join b in db.VABC_JS_ProductAndMeterial on a.材料ID equals b.材料ID
                                   into mytemps
                                   where a.作业中心ID == Convert.ToInt32(CenterId)
                                       && a.中间体ID == PIPId && a.会计期间ID == MyAp
                                    && a.手工调整 == CheckBox_Shift.Checked
                                   orderby a.材料ID
                                   from mytemp in mytemps.DefaultIfEmpty()
                                   select new
                                   {
                                       会计期间 = a.会计期间ID,
                                       材料ID = a.材料ID,
                                       计量单位 = a.计量单位,
                                       期初数量 = a.期初数量,
                                       期初金额 = a.期初金额,
                                       领用金额 = a.领用金额,
                                       耗用金额 = a.耗用金额,
                                       期末金额 = a.期末金额,
                                       领用数量 = a.领用数量,
                                       本期耗用 = a.本期耗用,
                                       期末数量 = a.期末数量,
                                       材料名称 = (mytemp == null ? "" : (mytemp.材料名称.Length > 10 ? mytemp.材料名称.Substring(0, 7) + "..." : mytemp.材料名称)),
                                       作业中心ID = a.作业中心ID,
                                       ID = a.ID,
                                       手工调整 = (a.手工调整 == false ? "否" : "是")
                                   };


                GridView_Meterial.DataSource = MyMeterialQuery1;
                GridView_Meterial.DataBind();

                if (GridView_Meterial.Rows.Count == 0)
                { Button_Save_1.Visible = false; }
                else
                { Button_Save_1.Visible = true; }
            }
            else
            { 

            var MyMeterialQuery2 = from a in db.TABC_JC_MeterialResumption
                                   join b in db.VABC_JS_ProductAndMeterial on a.材料ID equals b.材料ID
                                   into mytemps
                                   where a.作业中心ID == Convert.ToInt32(CenterId)
                                       && a.中间体ID == PIPId && a.会计期间ID == MyAp
                                
                                   orderby a.材料ID
                                   from mytemp in mytemps.DefaultIfEmpty()
                                   select new
                                   {
                                       会计期间 = a.会计期间ID,
                                       材料ID = a.材料ID,
                                       计量单位 = a.计量单位,
                                       期初数量 = a.期初数量,
                                       期初金额 = a.期初金额,
                                       领用金额 = a.领用金额,
                                       耗用金额 = a.耗用金额,
                                       期末金额 = a.期末金额,
                                       领用数量 = a.领用数量,
                                       本期耗用 = a.本期耗用,
                                       期末数量 = a.期末数量,
                                       材料名称 = (mytemp == null ? "" : (mytemp.材料名称.Length > 10 ? mytemp.材料名称.Substring(0, 7) + "..." : mytemp.材料名称)),
                                       作业中心ID = a.作业中心ID,
                                       ID = a.ID,
                                       手工调整 = (a.手工调整 == false ? "否" : "是")
                                   };


            GridView_Meterial.DataSource = MyMeterialQuery2;
            GridView_Meterial.DataBind();

            if (GridView_Meterial.Rows.Count == 0)
            { Button_Save_1.Visible = false; }
            else
            { Button_Save_1.Visible = true; }
            }
            
         



        }

        protected void Button_Save_Click(object sender, EventArgs e)
        {
            if ( HiddenField_Ap.Value.ToString() != Application["accountPeriod"].ToString())
            {

                alert = "<script>alert('非当前会计期间数据不能修改');</script>";
            
                return;
            }


            if (!Page.IsValid)
            {
              
                alert = "<script>alert('非法数据输入,请修改');</script>";
                return;
            }




            try
            {
                for (int i = 0; i < GridView_Meterial.Rows.Count; i++)
                {
                    int myid = Convert.ToInt32(GridView_Meterial.DataKeys[i]["ID"].ToString());

                    string myGetValue = ((TextBox)GridView_Meterial.Rows[i].Cells[6].FindControl("TextBox_GetValue")).Text;
                    string myGetMoney = ((TextBox)GridView_Meterial.Rows[i].Cells[7].FindControl("TextBox_GetMoney")).Text;
                    string myFinalnum = ((TextBox)GridView_Meterial.Rows[i].Cells[10].FindControl("TextBox_FinalValue")).Text;
                    var myrow = (from a in db.TABC_JC_MeterialResumption
                                 where a.ID == myid
                                 select a).Single();
                   
                    if (string.Format("{0:f4}", myrow.领用数量) != myGetValue
                         || string.Format("{0:f2}", myrow.领用金额) != myGetMoney
                         || string.Format("{0:f4}", myrow.期末数量) != myFinalnum)
                    {
                        myrow.手工调整 = true;

                    }


                    if (myGetValue == "")
                    { 
                      myrow.领用数量 = 0;
                    }
                    else
                    {
                        myrow.领用数量 = Convert.ToDecimal(myGetValue);                                              
                    }

                    if (myGetMoney == "")
                    {
                        myrow.领用金额 = 0;
                    }
                    else
                    {
                        myrow.领用金额 = Convert.ToDecimal(myGetMoney);
                    }

                    if (myFinalnum == "")
                    {
                        myrow.期末数量= 0;
                    }
                    else
                    {
                        myrow.期末数量 = Convert.ToDecimal(myFinalnum);
                    }




                }
                db.SubmitChanges();
            
                alert = "<script>alert('修改数据成功');</script>";

                BindData();
            }
            catch
            {
               
                alert = "<script>alert('修改数据出错，请与管理员联系');</script>";
            }
        }

        protected void Button_Del_Command(object sender, CommandEventArgs e)
        {

            if (HiddenField_Ap.Value.ToString() != Application["accountPeriod"].ToString())
            {

              
                alert = "<script>alert('非当前会计期间数据不能修改');</script>";

                return;
            }


            int myid = Convert.ToInt32(e.CommandArgument.ToString());

            var myrow = (from a in db.TABC_JC_MeterialResumption
                         where a.ID == myid
                         select a).Single();
            if (myrow.期初数量 != 0  || myrow.期初金额 !=0)
            {

                alert = "<script>alert('存在期初数量和金额的数据，不能删除');</script>";

                return;
            }
            else
            {


                db.TABC_JC_MeterialResumption.DeleteOnSubmit(myrow);
                db.SubmitChanges();

                BindData();
            
            
            }


        }

        protected void Button_Add_Click(object sender, EventArgs e)
        {
            if (HiddenField_Ap.Value.ToString() != Application["accountPeriod"].ToString())
            {

                alert = "<script>alert('非当前会计期间数据不能增加');</script>";
                return;
            }

            string MyCenterId = dropCostCenterSelect.SelectedValue;
            string MyPIPId = DropDownListSelectProductInProccess.SelectedValue;
            Response.Redirect("InsertDirectMeterial.aspx?centerid=" + MyCenterId + "&PIPid=" + MyPIPId);
        }



        //定义全局变量，并对列数据绑定事件进行编程。以显示汇总数据
        decimal total_First = 0;
        decimal total_Input = 0;
        decimal total_Used = 0;
        decimal total_Final = 0;

        protected void GridView_Meterial_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            // decimal totalcash = 0;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                total_First += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "期初金额"));
                total_Input += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "领用金额"));
                total_Used += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "耗用金额"));
                total_Final += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "期末金额"));


            }
            else if (e.Row.RowType == DataControlRowType.Footer)
            {
                e.Row.Cells[1].Text = "合计";

                e.Row.Cells[5].Text = String.Format("{0:N2}", total_First);

                e.Row.Cells[7].Text = String.Format("{0:N2}", total_Input);

                e.Row.Cells[9].Text = String.Format("{0:N2}", total_Used);

                e.Row.Cells[11].Text = String.Format("{0:N2}", total_Final);


            }
        }


    }
}
